package activator;

import library.service.Book;
import library.service.LibraryService;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogService;

import tracker.LogServiceListener;

public class ImprovedLibraryConsumerActivator implements BundleActivator {

	private LogServiceListener logListener;

	// --- Implementation of BundleActivator interface -------------------------
	public void start(BundleContext bundleContext) throws Exception {

		// init logging
		logListener = new LogServiceListener(bundleContext);

		// get service
		ServiceReference libraryServiceReference = bundleContext
				.getServiceReference(LibraryService.class.getName());
		LibraryService libraryService = null;
		if (libraryServiceReference != null) {
			libraryService = (LibraryService) bundleContext
					.getService(libraryServiceReference);
		}

		if (libraryService != null) {
			// test service
			logListener.getLog().log(LogService.LOG_INFO, "GET LibraryService");
			testListBooksMethod(libraryServiceReference, libraryService);
		}

		// clean up ServiceReference,Service,LogListener after use
		if (libraryService != null) {
			logListener.getLog().log(LogService.LOG_INFO,
					"UNGET LibraryService");
			bundleContext.ungetService(libraryServiceReference);
		}
		libraryService = null;
		libraryServiceReference = null;
	}

	public void stop(BundleContext context) throws Exception {
		logListener.stop();
	}

	// --- LibraryService related methods --------------------------------------
	private void testListBooksMethod(ServiceReference libraryServiceReference,
			LibraryService libraryService) {

		logListener.getLog().log(LogService.LOG_INFO, "testListBooksMethod()");

		if (libraryService == null) {
			return;
		}

		Book[] techBooks = libraryService.listBooks();

		// prepare listBook info message
		StringBuffer strBuffer = new StringBuffer(30);
		strBuffer.append("Books: ");
		for (int i = 0; i < techBooks.length; i++) {
			strBuffer.append(techBooks[i].getName());
			if (i != techBooks.length - 1) {
				strBuffer.append(", ");
			}
		}
		logListener.getLog().log(LogService.LOG_INFO, strBuffer.toString());

		// logging info
		logListener.getLog().log(
				LogService.LOG_INFO,
				"libraryService property 'category': "
						+ getCategoryProperty(libraryServiceReference));
		logListener.getLog().log(LogService.LOG_INFO, "------------------");

	}

	// --- Auxiliary methods ---------------------------------------------------

	private String getCategoryProperty(ServiceReference serviceReference) {
		return (String) serviceReference.getProperty("category");
	}
}
